import classnames from 'classnames';
import { useEffect, useRef } from 'react';
import styles from './index.module.scss';

interface TextareaType
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  value: string;
}
export default function Textarea(props: TextareaType) {
  // autoFocus=true给默认值
  const { className, value, maxLength, autoFocus = true, ...restProps } = props;
  //   创建ref,
  const iptRef = useRef<HTMLTextAreaElement>(null);
  useEffect(() => {
    iptRef.current?.setSelectionRange(-1, -1); ///setSelectionRange控制光标位置
  }, []);
  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={iptRef}
        className={classnames('textarea', className)}
        value={value}
        {...restProps}
        // 解构的东西要放回去，不然会消失
        maxLength={maxLength}
        autoFocus={autoFocus}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {/* {value?.length || 0}/{maxLength} */}
        {value.length}/{maxLength}
      </div>
    </div>
  );
}
